/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package roles;

import avenue.ErrorBox;
import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import model.DBManager;
import model.Module;
import model.RolePermission;
import model.UserRole;
import users.*;

/**
 *
 * @author Aggelos
 */
public class EditRoleForm extends javax.swing.JFrame {

    /**
     * Creates new form EditUserForm
     */
    public EditRoleForm() {
        em = DBManager.em;
        initComponents();
    }
    
     public EditRoleForm(UserRole ur, boolean readOnly) {
        em = DBManager.em;
        if ( !(em.getTransaction().isActive()) ){
            em.getTransaction().begin();
        }     
        userRole1=ur;
        this.readOnly = readOnly;
        initComponents();
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        userRole2 = userRole1;
        query1 = em.createQuery("select rp from RolePermission rp where rp.roleId=:userRole").setParameter("userRole",userRole2);
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        roleBoxRenderer1 = new avenue.RoleBoxRenderer();
        moduleQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select m from Module m");
        moduleList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : moduleQuery.getResultList();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        insertButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        delButton = new javax.swing.JButton();

        roleBoxRenderer1.setText("roleBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Όνομα Ρόλου : ");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRole2, org.jdesktop.beansbinding.ELProperty.create("${roleName}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        jButton1.setText("Αποθήκευση");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton2.setText("Ακυρο");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list1, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${moduleId.description}"));
        columnBinding.setColumnName("Υποσύστημα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canCreate}"));
        columnBinding.setColumnName("Δημιουργία");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canRetrieve}"));
        columnBinding.setColumnName("Προβολή");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canUpdate}"));
        columnBinding.setColumnName("Ενημέρωση");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canDelete}"));
        columnBinding.setColumnName("Διαγραφή");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationLevelAccess}"));
        columnBinding.setColumnName("Τοπική Πρ/ση");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(200);

        insertButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        insertButton.setText("Εισαγωγή");
        insertButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertButtonActionPerformed(evt);
            }
        });

        editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editButton.setText("Μεταβολή");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        delButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        delButton.setText("Διαγραφή");
        delButton.setToolTipText("");
        delButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(insertButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(delButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(insertButton)
                    .addComponent(editButton)
                    .addComponent(delButton)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
       this.setVisible(false); 
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
       }
       this.setVisible(false); 
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
        s=jTable1.getSelectedRow();
        if (s>=0) {
            
            RolePermission rp = list1.get(jTable1.getSelectedRow());
            em.persist(rp);
          
            EditPermissions epf = new EditPermissions(rp);
            //ο τίτλος της φόρμας αλλάζει ανάλογα με το τί κάνει (εισαγωγή / επεξεργασία)
            epf.setTitle("Επεξεργασία Δικαιώματος"); 
            epf.setVisible(true);
            thisFrame=this;
            thisFrame.setEnabled(false);

            epf.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                   if (((MyWindowEvent)arg0).exitAndSave){
                        jTable1.setRowSelectionInterval(s, s);
                        jTable1.scrollRectToVisible(jTable1.getCellRect(s, 0, true));
                        thisFrame.setEnabled(true);
                        java.util.Collection data = query1.getResultList();
                        for (Object entity : data) {
                            em.refresh(entity);
                        }
                        list1.clear();
                        list1.addAll(data);

                    }
                    else{
                        thisFrame.setEnabled(true);
                        em.getTransaction().rollback();
                        em.getTransaction().begin();
                        java.util.Collection data = query1.getResultList();
                        for (Object entity : data) {
                            em.refresh(entity);
                        }
                        list1.clear();
                        list1.addAll(data);
                    }
                }
                public void windowActivated(WindowEvent arg0) {
                    //System.out.println("Window Activated");
                }
                public void windowClosing(WindowEvent arg0) {
                    //System.out.println("Window Closing");
                }
                public void windowDeactivated(WindowEvent arg0) {
                    //System.out.println("Window Deactivated");
                    thisFrame.setEnabled(true);
                }
                public void windowDeiconified(WindowEvent arg0) {
                    //System.out.println("Window Deiconified");
                }
                public void windowIconified(WindowEvent arg0) {
                    //System.out.println("Window Iconified");
                }
                public void windowOpened(WindowEvent arg0) {
                    //System.out.println("Window Opened");
                }
            });
            }
        
    }//GEN-LAST:event_editButtonActionPerformed

    private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertButtonActionPerformed
        if (userRole1.getRolePermissionList()==null) userRole1.setRolePermissionList(new ArrayList<RolePermission>());
        
        //Έλεγχος εάν δεν υπάρχουν modules που δεν χρησιμοποιούνται
        if (userRole1.getRolePermissionList().size()==6){
            (new ErrorBox("Όλα τα διαθέσιμα modules χρησιμοποιούνται ήδη!")).setVisible(true);
            return;
        }
        
        RolePermission newrp=new RolePermission();
        newrp.setCanCreate(new Integer(1));
        newrp.setCanRetrieve(new Integer(1));
        newrp.setCanUpdate(new Integer(1));
        newrp.setCanDelete(new Integer(1));
        newrp.setStationLevelAccess(new Integer(1));
        newrp.setRoleId(userRole1);
        newrp.setModuleId(moduleList.get(0));
        em.persist(newrp);
        
        String[] cblist=new String[6-userRole1.getRolePermissionList().size()];
        System.out.print(userRole1.getRolePermissionList().size());
        int j=0;
        
        for (Module m: moduleList){
            boolean found=false;
            for(int i=0;i<userRole1.getRolePermissionList().size();i++){
                if (userRole1.getRolePermissionList().get(i).getModuleId().getDescription().equalsIgnoreCase(m.getDescription())) found=true;
            }
            if (!found) {
                System.out.println(m.getDescription());
                cblist[j++]=m.getDescription();
                
            }
        }
        userRole1.getRolePermissionList().add(newrp);
        EditPermissions epf = new EditPermissions(newrp, cblist);
        //ο τίτλος της φόρμας αλλάζει ανάλογα με το τί κάνει (εισαγωγή / επεξεργασία)
        epf.setTitle("Εισαγωγή Δικαιώματος"); 
        epf.setVisible(true);
        thisFrame=this;
        thisFrame.setEnabled(false);

        epf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
               System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    thisFrame.setEnabled(true);
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                    
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = query1.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    list1.clear();
                    list1.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                //System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                //System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                //System.out.println("Window Deactivated");
                thisFrame.setEnabled(true);
            }
            public void windowDeiconified(WindowEvent arg0) {
                //System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                //System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                //System.out.println("Window Opened");
            }
        });
        
    }//GEN-LAST:event_insertButtonActionPerformed

    private void delButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButtonActionPerformed
        int s=jTable1.getSelectedRow();
        if (s>=0) {
            RolePermission drp = list1.get(jTable1.convertRowIndexToModel(s));
            userRole1.getRolePermissionList().remove(drp);
            list1.remove(drp);
            em.remove(drp);
        }
    }//GEN-LAST:event_delButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditUserForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditRoleForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton delButton;
    private javax.swing.JButton editButton;
    private javax.swing.JButton insertButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private java.util.List<RolePermission> list1;
    private java.util.List<Module> moduleList;
    private javax.persistence.Query moduleQuery;
    private javax.persistence.Query query1;
    private avenue.RoleBoxRenderer roleBoxRenderer1;
    private model.UserRole userRole2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    UserRole userRole1;
    boolean readOnly;
    JFrame thisFrame;
    int s;
}
